import { ErrorTypes, handleError, withRetry } from '@/utils/errorHandler';

const WEATHER_KEY = 'SskzkvNgwBuSQCKcO';
// 使用一言API - 稳定的名言接口
const QUOTES_API = 'https://v1.hitokoto.cn/?c=d&c=i&c=k';
const BACKGROUND_API = 'https://picsum.photos/1080/1920';
const ALMANAC_API = 'https://api.tiax.cn/almanac/';

// 检查API响应
const checkResponse = (response, type = 'default') => {
    if (!response.data) {
        throw new Error('API返回数据为空');
    }

    switch (type) {
        case 'weather':
            // 检查天气数据格式
            if (!response.data.results || !response.data.results[0]) {
                throw new Error('天气数据格式错误');
            }
            console.log(response.data.results[0], 'response.data.results[0]');
            return {
                location: response.data.results[0].location,
                now: {
                    ...response.data.results[0].now,
                },
                lastUpdate: response.data.results[0].last_update,
            };

        case 'quote':
            try {
                // 一言API返回格式: { hitokoto: '内容', from: '来源', from_who: '作者' }
                if (!response.data?.hitokoto) {
                    throw new Error('名言数据格式错误');
                }

                return {
                    text: response.data.hitokoto,
                    author: response.data.from_who || response.data.from || '佚名',
                };
            } catch (error) {
                console.error('解析名言数据失败:', error);
                throw new Error('名言数据解析失败');
            }

        case 'forecast':
            if (!response.data?.results?.[0]?.daily) {
                throw new Error('天气预报数据格式错误');
            }
            return response.data.results[0];

        case 'almanac':
            if (!response.data.公历日期) {
                throw new Error('农历数据格式错误');
            }
            return response.data;

        default:
            return response.data;
    }
};

export const getWeather = async (location) => {
    try {
        const response = await withRetry(() =>
            uni.request({
                url: `https://api.seniverse.com/v3/weather/now.json`,
                data: {
                    key: WEATHER_KEY,
                    location,
                    language: 'zh-Hans',
                    unit: 'c',
                },
            })
        );

        const weatherData = checkResponse(response, 'weather');

        // 如果当前天气数据缺少湿度或风速
        if (!weatherData.now.humidity || !weatherData.now.wind_speed) {
            try {
                // 获取天气预报数据
                const forecastData = await getWeatherForecast(location);
                // 使用今天的预报数据
                const todayForecast = forecastData[0];

                return {
                    ...weatherData,
                    location: {
                        name: weatherData.location.name,
                        province: weatherData.location.province,
                        city: weatherData.location.city,
                        district: weatherData.location.district,
                    },
                    now: {
                        ...weatherData.now,
                        // 如果当前数据缺失，使用预报数据
                        humidity:
                            weatherData.now.humidity || todayForecast.humidity,
                        wind_speed:
                            weatherData.now.wind_speed ||
                            todayForecast.windSpeed,
                        wind_direction:
                            weatherData.now.wind_direction ||
                            todayForecast.windDirection,
                        feels_like:
                            weatherData.now.feels_like ||
                            weatherData.now.temperature,
                    },
                };
            } catch (forecastError) {
                console.error('获取天气预报失败:', forecastError);
                // 如果获取预报也失败，使用默认值
                return {
                    ...weatherData,
                    location: {
                        name: weatherData.location.name,
                        province: weatherData.location.province,
                        city: weatherData.location.city,
                        district: weatherData.location.district,
                    },
                    now: {
                        ...weatherData.now,
                        humidity: weatherData.now.humidity || 0,
                        wind_speed: weatherData.now.wind_speed || 0,
                        wind_direction: weatherData.now.wind_direction || '',
                        feels_like:
                            weatherData.now.feels_like ||
                            weatherData.now.temperature,
                    },
                };
            }
        }

        // 如果数据完整，直接返回
        return {
            ...weatherData,
            location: {
                name: weatherData.location.name,
                province: weatherData.location.province,
                city: weatherData.location.city,
                district: weatherData.location.district,
            },
            now: {
                ...weatherData.now,
                humidity: weatherData.now.humidity,
                wind_speed: weatherData.now.wind_speed,
                wind_direction: weatherData.now.wind_direction || '',
                feels_like:
                    weatherData.now.feels_like || weatherData.now.temperature,
            },
        };
    } catch (error) {
        if (error.errMsg?.includes('request:fail')) {
            handleError(error, ErrorTypes.NETWORK);
        } else {
            handleError(error, ErrorTypes.API);
        }
        throw error;
    }
};

export const getQuote = async () => {
    try {
        const response = await withRetry(() =>
            uni.request({
                url: QUOTES_API,
            })
        );
        return checkResponse(response, 'quote');
    } catch (error) {
        handleError(error, ErrorTypes.API);
        throw error;
    }
};

export const getRandomBackground = () => {
    try {
        return `${BACKGROUND_API}?random=${Date.now()}`;
    } catch (error) {
        handleError(error, ErrorTypes.API);
        // 返回默认背景图
        return '/static/default-bg.jpg';
    }
};

export const getLocation = () => {
    return new Promise((resolve, reject) => {
        uni.getLocation({
            type: 'gcj02',
            success: (res) => {
                resolve({
                    latitude: res.latitude,
                    longitude: res.longitude,
                });
            },
            fail: (error) => {
                handleError(error, ErrorTypes.LOCATION);
                reject(error);
            },
        });
    });
};

export const getWeatherForecast = async (location) => {
    try {
        const response = await withRetry(() =>
            uni.request({
                url: `https://api.seniverse.com/v3/weather/daily.json`,
                data: {
                    key: WEATHER_KEY,
                    location,
                    language: 'zh-Hans',
                    unit: 'c',
                    start: 0,
                    days: 3,
                },
            })
        );

        const forecastData = checkResponse(response, 'forecast');
        return forecastData.daily.map((day) => ({
            date: day.date,
            dayWeather: day.text_day,
            nightWeather: day.text_night,
            high: day.high,
            low: day.low,
            windDirection: day.wind_direction,
            windSpeed: day.wind_speed,
            humidity: day.humidity,
        }));
    } catch (error) {
        handleError(error, ErrorTypes.API);
        throw error;
    }
};

export const getAlmanac = async () => {
    try {
        const response = await withRetry(() =>
            uni.request({
                url: ALMANAC_API,
            })
        );

        const almanacData = checkResponse(response, 'almanac');
        return {
            solarDate: almanacData.公历日期,
            lunarDate: almanacData.农历日期,
            yellowDate: almanacData.黄历日期,
            islamicDate: almanacData.回历日期,
            ganzhi: almanacData.干支日期,
            wuxing: almanacData.五行纳音,
            godOfDay: almanacData.值日星神,
            suitable: almanacData.宜,
            unsuitable: almanacData.忌,
        };
    } catch (error) {
        handleError(error, ErrorTypes.API);
        throw error;
    }
};
